package com.quanyan.thread;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

import org.apache.log4j.Logger;

import com.quanyan.cache.SocketChannelMng;
import com.quanyan.entity.ChannelContext;
import com.quanyan.entity.Command;
import com.quanyan.entity.RemindTask;

/**
 * 
 * @ClassName: MessageRemindThread
 * @Description:消息推送
 * @author chuntu tuchun168@163.com
 * @date 2016年5月3日 上午11:21:50
 *
 */
public class MessageRemindThread {
	private static Logger log = Logger.getLogger(MessageRemindThread.class);

	private static BlockingQueue<RemindTask> taskQueue = new LinkedBlockingDeque<RemindTask>();

	// 线程池中默认线程的个数为5
	private static int worker_num = 5;

	// 工作线程
	private static WorkThread[] workThrads;

	public MessageRemindThread() {

		workThrads = new WorkThread[worker_num];
		for (int i = 0; i < worker_num; i++) {
			workThrads[i] = new WorkThread();
			workThrads[i].start();// 开启线程池中的线程
		}
	}

	public static void putRemindTask(RemindTask task)
			throws InterruptedException {
		taskQueue.put(task);
	}

	// 返回任务队列
	public static BlockingQueue<RemindTask> getTaskQueue() {
		return taskQueue;
	}

	private class WorkThread extends Thread {
		@Override
		public void run() {
			while (true) {
				System.out.println("中间件消息推送线程开始推送了");
				try {
					RemindTask task = taskQueue.take();
					Long friendId = task.getFriendid();
					Command command = task.getCommand();
					SocketChannelMng socketChannelMng = SocketChannelMng
							.getInstance();
					ChannelContext channelContext = socketChannelMng
							.getUserSocketChannel(friendId);
					System.out.println(task.getUserid() + "推送任务给：" + friendId);
					channelContext.getChannel().write(command);
				} catch (InterruptedException e) {
					log.error("推送线程异常：" + e.getMessage(), e);
				}
			}
		}
	}

}
